import tkinter as tk
from tkinter import ttk, simpledialog
from fangfa import ExcelHandler
from datetime import datetime


class TradeRecordGUI:
    def __init__(self, root, excel_handler):
        self.root = root
        self.root.title("交易记录软件")
        self.root.minsize(400,400)
        #self.root.maxsize(400,400)
        self.excel_handler = excel_handler
        self.trade_type = '买入'
        self.all_categories = self.excel_handler.get_categories()

        self.create_widgets()

    def create_widgets(self):
        # 品类选择下拉菜单及搜索框
        category_frame = tk.Frame(self.root)
        category_frame.pack(pady=10)

        self.category_var = tk.StringVar()
        self.category_combobox = ttk.Combobox(category_frame, textvariable=self.category_var,
                                              values=self.all_categories)
        self.category_combobox.set('示例品类')
        self.category_combobox.pack(anchor=tk.NE)
        self.category_combobox.bind("<<ComboboxSelected>>", lambda event: self.show_latest_records())

        #self.search_entry = tk.Entry(category_frame, width=15)
        #self.search_entry.pack(side=tk.LEFT, padx=5)

        #self.search_button = tk.Button(category_frame, text="搜索", command=self.search_categories)
        #self.search_button.pack(side=tk.LEFT, padx=5)

        # 交易信息输入框
        input_frame = tk.Frame(self.root)
        input_frame.pack(anchor=tk.NW, padx=10, pady=10)

        self.date_label = tk.Label(input_frame, text="交易日期 (YYYY-MM-DD):")
        self.date_label.pack(anchor=tk.W)
        self.date_entry = tk.Entry(input_frame)
        current_date = datetime.now().strftime('%Y-%m-%d')
        self.date_entry.insert(0, current_date)
        self.date_entry.pack(anchor=tk.W)

        self.quantity_label = tk.Label(input_frame, text="数量:")
        self.quantity_label.pack(anchor=tk.W)
        # 为数量输入框添加验证
        vcmd_quantity = (self.root.register(self.validate_number), '%P')
        self.quantity_entry = tk.Entry(input_frame, validate='key', validatecommand=vcmd_quantity)
        self.quantity_entry.pack(anchor=tk.W)

        self.price_label = tk.Label(input_frame, text="价格:")
        self.price_label.pack(anchor=tk.W)
        # 为价格输入框添加验证
        vcmd_price = (self.root.register(self.validate_number), '%P')
        self.price_entry = tk.Entry(input_frame, validate='key', validatecommand=vcmd_price)
        self.price_entry.pack(anchor=tk.W)

        # 买入/卖出按钮
        button_frame = tk.Frame(self.root)
        button_frame.pack(anchor=tk.SW, padx=10, pady=10)

        self.buy_button = tk.Button(button_frame, text="买入", command=lambda: self.save_record('买入'))
        self.buy_button.pack(side=tk.LEFT, padx=5)
        self.sell_button = tk.Button(button_frame, text="卖出", command=lambda: self.save_record('卖出'))
        self.sell_button.pack(side=tk.LEFT, padx=5)

        #self.save_button = tk.Button(button_frame, text="保存记录", command=self.save_record)
        #self.save_button.pack(side=tk.LEFT, padx=5)

        # 品类操作按钮
        category_operation_frame = tk.Frame(self.root)
        category_operation_frame.pack(anchor=tk.SW, padx=10, pady=10)

        self.add_button = tk.Button(category_operation_frame, text="添加品类", command=self.show_add_category_dialog)
        self.add_button.pack(side=tk.LEFT, padx=5)
        self.modify_button = tk.Button(category_operation_frame, text="修改品类", command=self.modify_category)
        self.modify_button.pack(side=tk.LEFT, padx=5)

        # 显示最新 10 条记录
        # 显示最新 10 条记录的表格
        self.records_tree = ttk.Treeview(self.root, columns=('交易日期', '数量', '价格', '交易类型'), show='headings')
        self.records_tree.heading('交易日期', text='交易日期')
        self.records_tree.heading('数量', text='数量')
        self.records_tree.heading('价格', text='价格')
        self.records_tree.heading('交易类型', text='交易类型')
        self.records_tree.pack(anchor=tk.SE, padx=10, pady=10)

        self.show_latest_records()

    def validate_number(self, new_value):
        """验证输入是否为数字"""
        if new_value == "":
            return True
        try:
            float(new_value)
            return True
        except ValueError:
            return False

    def set_trade_type(self, trade_type):
        self.trade_type = trade_type

    def save_record(self,trade_type):
        category = self.category_var.get()
        date = self.date_entry.get()
        quantity = self.quantity_entry.get()
        price = self.price_entry.get()

        if not date or not quantity or not price:
            tk.messagebox.showerror("错误", "请填写完整的交易信息（日期、数量、价格）。")
            return

        self.excel_handler.save_record(category, date, quantity, price, self.trade_type)
        self.show_latest_records()
        self.clear_entries()
        current_date = datetime.now().strftime('%Y-%m-%d')
        self.date_entry.insert(0, current_date)
        tk.messagebox.showinfo("成功", f"{self.trade_type} 记录已保存。")

    def show_latest_records(self):
        category = self.category_var.get()
        latest_records = self.excel_handler.get_latest_records(category)

        # 清空表格
        for i in self.records_tree.get_children():
            self.records_tree.delete(i)

        # 插入新数据
        for index, row in latest_records.iterrows():
            self.records_tree.insert('', 'end', values=(row['交易日期'], row['数量'], row['价格'], row['交易类型']))

    def clear_entries(self):
        self.date_entry.delete(0, tk.END)
        self.quantity_entry.delete(0, tk.END)
        self.price_entry.delete(0, tk.END)

    def show_add_category_dialog(self):
        new_category = simpledialog.askstring("添加品类", "请输入新的品类名称:")
        if new_category:
            if self.excel_handler.add_category(new_category):
                self.all_categories = self.excel_handler.get_categories()
                self.update_category_combobox(self.all_categories)
                self.category_combobox.set(new_category)
                self.show_latest_records()

    def modify_category(self):
        old_category = self.category_var.get()
        new_category = simpledialog.askstring("修改品类", f"请输入新的品类名称来替换 {old_category}:")
        if new_category:
            if self.excel_handler.rename_sheet(old_category, new_category):
                self.all_categories = self.excel_handler.get_categories()
                self.update_category_combobox(self.all_categories)
                self.category_combobox.set(new_category)
                self.show_latest_records()

    def update_category_combobox(self, categories):
        self.category_combobox['values'] = categories

    def search_categories(self):
        keyword = self.search_entry.get().strip()
        if keyword:
            filtered_categories = [cat for cat in self.all_categories if keyword in cat]
            self.update_category_combobox(filtered_categories)
        else:
            self.update_category_combobox(self.all_categories)


if __name__ == "__main__":
    root = tk.Tk()
    excel_handler = ExcelHandler()
    app = TradeRecordGUI(root, excel_handler)
    root.mainloop()